import store from '@/store'
import axios from 'axios'
import router from '@/router'
import { Message } from 'element-ui'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url//基地址
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout//请求超时时间，超过报错
})

const time = 30000000

// request interceptor请求拦截器
service.interceptors.request.use(config => {
  // console.log(config)
  if (store.state.user.token) {
    const curTime = Date.now()
    const dir = curTime - localStorage.getItem('loginTime')
    if (dir > time) {
      // 登出
      store.dispatch('user/logout')
      // 跳转登录页
      router.push(`/login`)
      return Promise.reject(new Error('token失效，请重新登录！'))
    }
    config.headers.Authorization = `Bearer ${store.state.user.token}`
  }
  return config
}

)

// response interceptor响应拦截器
service.interceptors.response.use(response => {
  console.log('网络层面成功')
  const { data, message, success } = response.data
  if (success) {
    console.log('数据层面成功')
    // this.$massage.success(message)
    if (response.config.method !== 'get' && response.config.url !== '/api/sys/profile') {
      Message.success(message)
    }
    return data
  } else {
    Message.error(message)
    return Promise.reject(new Error(message))
  }
},
err => {
  console.log('网络层面失败', err)

  console.dir(err)
  // token失效了,要添加短路运算，err.response是后端返回的数据，而err不一定都是后端返回的数据
  if (err.response && err.response.data.code === 10002) {
    // 登出
    store.dispatch('user/logout')
    // 跳转登录页
    router.push(`/login`)
  }
  Message.error(err.message)
  return Promise.reject(err)
}
)

export default service
